package models

import (
	"fmt"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/config"
	_ "github.com/go-sql-driver/mysql"
)

// 初始化数据库连接
func init() {
	// 从配置文件获取数据库配置
	dbHost, _ := config.String("dbhost")
	dbPort, _ := config.String("dbport")
	dbUser, _ := config.String("dbuser")
	dbPassword, _ := config.String("dbpassword")
	dbName, _ := config.String("dbname")

	// 构建连接字符串
	dsn := dbUser + ":" + dbPassword + "@tcp(" + dbHost + ":" + dbPort + ")/" + dbName + "?charset=utf8mb4&loc=Local"

	// 注册数据库驱动
	orm.RegisterDriver("mysql", orm.DRMySQL)

	// 注册默认数据库
	orm.RegisterDataBase("default", "mysql", dsn)

	// 设置数据库最大空闲连接数
	orm.SetMaxIdleConns("default", 30)

	// 设置数据库最大打开连接数
	orm.SetMaxOpenConns("default", 100)

	// 注册模型
	registerModels()
	// 自动同步数据库表结构
	err := orm.RunSyncdb("default", false, true)
	if err != nil {
		fmt.Printf("同步数据库表结构失败: %v\n", err)
	}
	// 开发模式下，打印SQL语句
	runmode, _ := config.String("runmode")
	if runmode == "dev" {
		orm.Debug = true
	}
}

// 注册所有模型
func registerModels() {
	orm.RegisterModel(
		new(Cleaner),
		new(CleaningRecord),
		new(CleaningSetting),
		new(Douyin),
		new(DouyinGroup),
		new(DouyinGroupOrder),
		new(BookingSetting),
		new(Admin),
		new(Role),
		new(GroupBuyVerify),
		new(Permission),
		new(RolePermission),
		new(AdminRole),
		new(Franchise),
		new(Store),
		new(Room),
		new(Venue),
		new(VenuePackage),
		new(Member),
		new(MemberLevel),
		new(MemberCard),
		new(BalanceLog),
		new(PointsLog),
		new(Coupon),
		new(CouponIssue),
		new(CouponActivity),
		new(RechargePackage),
		new(RechargeRecord),
		new(GroupBuyActivity),
		new(GroupBuyOrder),
		new(GroupBuyStatistics),
		new(Order),
		new(PreOrder),
		new(Banner),
		new(PaymentChannel),
		new(Transaction),
		new(OperationLog),
		new(City),
		new(VenueType),
		new(MiniprogramConfig),
		new(MiniprogramContent),
		new(Refund),
		new(MemberCheckin),
		new(MemberCheckinDays),
		new(Favorite),
		new(Device),
		new(DeviceGroup),
		new(DeviceGroupRelation),
		new(Meituan),
		new(MeituanOrder),
	)
}

// BaseModel 基础模型，包含通用字段
type BaseModel struct {
	Id          int64  `orm:"pk;auto" json:"id"`
	FranchiseId int64  `orm:"" json:"franchise_id"` // 所属加盟商，关联Franchise表的ID字段
	CreatedAt   int64  `orm:"" json:"created_at"`   // 使用时间戳
	UpdatedAt   int64  `orm:"" json:"updated_at"`   // 使用时间戳
	CreatedBy   string `orm:"size(64)" json:"created_by"`
	UpdatedBy   string `orm:"size(64)" json:"updated_by"`
	IsDeleted   int8   `orm:"default(0)" json:"is_deleted"` // 软删除标记
}

// 在保存前自动设置时间戳
func (m *BaseModel) BeforeInsert() {
	currentTime := time.Now().Unix()
	m.CreatedAt = currentTime
	m.UpdatedAt = currentTime
}

// 在更新前自动设置更新时间
func (m *BaseModel) BeforeUpdate() {
	m.UpdatedAt = time.Now().Unix()
}

// GetOrm 获取ORM实例
func GetOrm() orm.Ormer {
	return orm.NewOrm()
}

// InitDB 初始化数据库连接
func InitDB() {
	// 从配置文件获取数据库配置
	dbHost, _ := config.String("dbhost")
	dbPort, _ := config.String("dbport")
	dbUser, _ := config.String("dbuser")
	dbPassword, _ := config.String("dbpassword")
	dbName, _ := config.String("dbname")

	// 构建连接字符串
	dsn := dbUser + ":" + dbPassword + "@tcp(" + dbHost + ":" + dbPort + ")/" + dbName + "?charset=utf8mb4&loc=Local"

	// 注册数据库驱动
	orm.RegisterDriver("mysql", orm.DRMySQL)

	// 注册默认数据库
	orm.RegisterDataBase("default", "mysql", dsn)

	// 设置数据库最大空闲连接数
	orm.SetMaxIdleConns("default", 30)

	// 设置数据库最大打开连接数
	orm.SetMaxOpenConns("default", 100)

	// 注册模型
	registerModels()

	// 开发模式下，打印SQL语句
	runmode, _ := config.String("runmode")
	if runmode == "dev" {
		orm.Debug = true
	}
}
